<template>
  <h1>{{ sum }}</h1>
  <button @click="sum++">点我+1</button>
  <br>
  <h1>你好 {{ msg }}</h1>
  <br>
  <button @click="msg += '1'">点我修改msg</button>

  <br>
  <h1>姓名：{{ person.name }}</h1>
  <h1>年龄：{{ person.age }}</h1>
  <h1>薪资：{{ person.job.j1.salary }}K</h1>
  <h1>薪资：{{ person.job.j2.salary }}K</h1>
  <button @click="person.name += '1'">点我修改姓名</button>
  <button @click="person.age++">点我修改年龄</button>
  <button @click="person.job.j1.salary++">涨薪</button>

  <hr />
</template>

<script>
import { ref, reactive, watch } from "vue";
export default {
  name: "App",
  setup() {
    const sum = ref(0);
    const msg = ref("Vue");
    const person = reactive({
      name: "张三",
      age: 18,
      job:{
        j1:{
          salary:20
        },
        j2:{
          salary:30
        }
      }
    });

    // 情况一：监听一个ref
    watch(
      sum,
      (newValue, oldValue) => {
        console.log("watch sum ref", newValue, oldValue);
      },
      { immediate: true }
    );

    // 情况二：监听多个ref
    watch(
      [sum, msg],
      (newValue, oldValue) => {
        console.log("watch sum,msg ref", newValue, oldValue);
      },
      { immediate: true }
    );

    // 情况三：监听一个reactive
    // 注意：默认开启深度监听
    watch(person, (newValue, oldValue) => {
      console.log("watch person reactive", newValue, oldValue);
    },{
    //   deep: false
    });

    // 情况四：监听一个reactive中的某个属性
    watch(
      () => person.name,
      (newValue, oldValue) => {
        console.log("watch person.name reactive", newValue, oldValue);
      }
    );

    // 情况五：监听一个reactive中的某些属性
    watch(
      [() => person.name, () => person.age],
      (newValue, oldValue) => {
        console.log("watch person.name,person.age reactive", newValue, oldValue);
      }
    );

    // 特殊情况
    // 如果侦听源是一个函数，且函数返回值为一个对象，默认仅当返回对象改变时才会触发回调，如果要深度监听，需要配置deep选项
    watch(
      () => person.job,
      (newValue, oldValue) => {
        console.log("特殊情况 watch person.job reactive", newValue, oldValue);
      },
      { deep: true }
    );

    return {
      person,
      sum,
      msg,
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
